using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class UpdateEmployeeCommandHandler : IRequestHandler<UpdateEmployeeCommand, EmployeeDto>
	{
		private readonly IBaseRepository<Employee> _repository;

		public UpdateEmployeeCommandHandler(IBaseRepository<Employee> repository)
		{
			_repository = repository;
		}

		public async Task<EmployeeDto> Handle(UpdateEmployeeCommand request, CancellationToken cancellationToken)
		{
			var entity = await _repository.GetModel(x => x.EmployeeId == request.EmployeeId && !x.IsDeleted);
			if (entity == null) throw new Exception("员工不存在");

			if (!string.IsNullOrEmpty(request.UserName)) entity.UserName = request.UserName;
			if (!string.IsNullOrEmpty(request.FullName)) entity.FullName = request.FullName;
			if (!string.IsNullOrEmpty(request.WorkNo)) entity.WorkNo = request.WorkNo;
			if (request.DepartmentId.HasValue) entity.DepartmentId = request.DepartmentId;
			if (request.Email != null) entity.Email = request.Email;
			if (request.Gender != null) entity.Gender = request.Gender;
			if (request.Address != null) entity.Address = request.Address;
			if (request.Phone != null) entity.Phone = request.Phone;
			if (request.IdCardNo != null) entity.IdCardNo = request.IdCardNo;
			if (request.Title != null) entity.Title = request.Title;
			if (request.Role != null) entity.Role = request.Role;
			if (request.IsActive.HasValue) entity.IsActive = request.IsActive.Value;

			entity.UpdatedAt = DateTime.Now;
			await _repository.UpdateAsync(entity);

			return new EmployeeDto
			{
				EmployeeId = entity.EmployeeId,
				UserName = entity.UserName,
				FullName = entity.FullName,
				WorkNo = entity.WorkNo,
				DepartmentId = entity.DepartmentId,
				Email = entity.Email,
				Gender = entity.Gender,
				Address = entity.Address,
				Phone = entity.Phone,
				IdCardNo = entity.IdCardNo,
				Title = entity.Title,
				Role = entity.Role,
				IsActive = entity.IsActive,
				CreatedAt = entity.CreatedAt,
				UpdatedAt = entity.UpdatedAt
			};
		}
	}
}
